package com.runa.monitor.platinterface.extend.hdb;

import com.hdb.api.adv.HdbData;
import com.hdb.api.base.FLTHWriteResult;
import com.runa.monitor.comm.pojo.Result;
import lombok.Data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 2023/10/31 15:44
 * zhangYB
 */
@Data
public class HdbResponse {

    private boolean success;
    private String msg;

    private List<HdbData> hdbDataList;
    private List<FLTHWriteResult> execResults;
    private List<HdbWriteResult> writeResults = new ArrayList<>();

    private Map<String, String> pointResultMap = new HashMap<>();

    public HdbResponse(Boolean success) {
        this.success = success;
    }

    public HdbResponse(boolean success, String msg) {
        this.success = success;
        this.msg = msg;
    }

    public static HdbResponse ok() {
        return new HdbResponse(true);
    }

    public static HdbResponse ok(String msg) {
        return new HdbResponse(true, msg);
    }

    public static HdbResponse error() {
        return new HdbResponse(false);
    }

    public static HdbResponse error(String msg) {
        return new HdbResponse(false, msg);
    }

    public HdbResponse hdbData(List<HdbData> hdbDataList) {
        this.hdbDataList = hdbDataList;
        return this;
    }
    public HdbResponse writeResults(List<HdbWriteResult> writeResults) {
        this.writeResults = writeResults;
        return this;
    }


    public void handle(List<String> pointCodes) {
        if (success) {
            for (int i = 0; i < hdbDataList.size(); i++) {
                HdbData hdbData = hdbDataList.get(i);
                String code = pointCodes.get(i);
                String value = String.valueOf(hdbData.value);
                this.pointResultMap.put(code, value);
            }
        }
    }


    public void addWriteResults(List<HdbWriteResult> writeResults) {
        this.writeResults.addAll(writeResults);
    }

    public int getCode() {
        if (!success) {
            return 500;
        }
        return 200;
    }

    public Result result() {
        Result result;
        if (success) {
            result = Result.success();
        } else {
            result = Result.error(msg);
        }
        return result;
    }
}
